<template>
  <div v-if="visible" class="lineup-modal-wrapper" @click="onMaskClick">
    <div class="lineup-modal" @click.stop>
      <!-- 标题与方案切换 -->
      <div class="modal-header">
        <div class="title-left">
          <span class="modal-title">阵容配置</span>
          <span class="modal-subtitle">与当前UI保持一致的卡片风格</span>
        </div>
        <div class="header-actions">
          <button class="header-btn" @click="addScheme">＋ 新增方案</button>
          <button class="header-btn close" @click="close">×</button>
        </div>
      </div>

      <div class="scheme-tabs">
        <div 
          v-for="(scheme, idx) in schemes" 
          :key="scheme.id" 
          class="tab-item"
          :class="{ active: activeSchemeIndex === idx }"
          @click="switchScheme(idx)"
        >
          <span class="tab-name">方案{{ idx + 1 }}</span>
          <span class="tab-status" v-if="scheme.modified">未保存</span>
        </div>
      </div>

      <!-- 阵容展示区域（重构） -->
      <div class="formation-area">
        
        <!-- 前排：3张卡牌水平排列 -->
        <div class="row front-row">
          <div 
            v-for="posKey in frontPositions" 
            :key="posKey" 
            class="lineup-card partner-card" 
            :class="{ 
              dragging: draggingPos === posKey,
              'drag-over': dragOverPos === posKey && draggingPos && draggingPos !== posKey
            }"
            draggable="true"
            @dragstart="onDragStart(posKey, $event)"
            @dragover.prevent="onDragOver(posKey, $event)"
            @drop="onDrop(posKey, $event)"
            @dragend="onDragEnd"
            @touchstart="onTouchStart(posKey, $event)"
            @touchmove.prevent="onTouchMove(posKey, $event)"
            @touchend="onTouchEnd(posKey, $event)"
            @click.stop="handleCardClick(posKey, $event)"
          >
            <!-- 去掉位置信息，只显示必要内容 -->
            <div class="slot-body">
              <template v-if="currentScheme.slots[posKey] && currentScheme.slots[posKey].partner_id !== 0">
                <div class="role-info">
                  <QualityText :quality="currentScheme.slots[posKey].pev" :text="currentScheme.slots[posKey].name" :bold="true" />
                  <div class="role-stats">
                    <span>血量: {{ currentScheme.slots[posKey].hp }}</span>
                    <span>伤害: {{ currentScheme.slots[posKey].base_damage }}</span>
                  </div>
                </div>
              </template>
              <template v-else>
                <div class="empty-tip">点击选择伙伴</div>
              </template>
            </div>
          </div>
        </div>

        <!-- 后排：3张卡牌水平排列，与前排对齐 -->
        <div class="row back-row">
          <div 
            v-for="posKey in backPositions" 
            :key="posKey" 
            class="lineup-card partner-card" 
            :class="{ 
              dragging: draggingPos === posKey,
              'drag-over': dragOverPos === posKey && draggingPos && draggingPos !== posKey
            }"
            draggable="true"
            @dragstart="onDragStart(posKey, $event)"
            @dragover.prevent="onDragOver(posKey, $event)"
            @drop="onDrop(posKey, $event)"
            @dragend="onDragEnd"
            @touchstart="onTouchStart(posKey, $event)"
            @touchmove.prevent="onTouchMove(posKey, $event)"
            @touchend="onTouchEnd(posKey, $event)"
            @click.stop="handleCardClick(posKey, $event)"
          >
            <!-- 去掉位置信息，只显示必要内容 -->
            <div class="slot-body">
              <template v-if="currentScheme.slots[posKey] && currentScheme.slots[posKey].partner_id !== 0">
                <div class="role-info">
                  <QualityText :quality="currentScheme.slots[posKey].pev" :text="currentScheme.slots[posKey].name" :bold="true" />
                  <div class="role-stats">
                    <span>血量: {{ currentScheme.slots[posKey].hp }}</span>
                    <span>伤害: {{ currentScheme.slots[posKey].base_damage }}</span>
                  </div>
                </div>
              </template>
              <template v-else>
                <div class="empty-tip">点击选择伙伴</div>
              </template>
            </div>
          </div>
        </div>
      </div>


      <!-- 操作区：保存、应用、管理 -->
      <div class="modal-actions">
        <button class="action-btn primary" @click="applyScheme">应用到当前阵容</button>
        <button class="action-btn danger" @click="clearFormation">清空阵容</button>
      </div>

      <!-- 伙伴选择弹层 -->
      <transition name="fade-slide">
        <div v-if="showSelector" class="selector-wrapper" @click="closeSelector">
          <div class="selector-panel" @click.stop>
            <div class="selector-header">
              <div class="selector-title">选择伙伴</div>
              <div class="selector-close" @click="closeSelector">×</div>
            </div>
            <!-- 品阶Tab筛选 -->
            <div class="selector-tabs">
              <div
                v-for="pev in displayPevs"
                :key="'pev-tab-' + pev"
                class="tab-item"
                :class="{ active: selectedPev === pev }"
                @click="selectedPev = pev"
              >品阶{{ pev }}</div>
            </div>

            <!-- 下拉选择模式：仅显示名称、生命、伤害 -->
            <div class="selector-controls">
              <label class="selector-label">从品阶{{ selectedPev || displayPevs[0] }}中选择伙伴：</label>
              <select class="partner-select" v-model="selectedPartnerId" @change="onPartnerSelectChange">
                <option :value="0">请选择伙伴</option>
                <option v-for="p in partnersInTab" :key="p.partner_id || p.id" :value="p.partner_id || p.id">
                  {{ p.name }} · 生命: {{ p.hp }} · 伤害: {{ p.base_damage }}
                </option>
              </select>
            </div>

            <button v-if="selectedMemberHasPartner" class="remove-btn" @click="removePartner">移除当前卡槽伙伴</button>
          </div>
        </div>
      </transition>
    </div>
  </div>
</template>

<script>
import api from '@/api'
import QualityText from '@/components/QualityText.vue'

export default {
  name: 'LineupConfigModal',
  components: { QualityText },
  props: {
    visible: { type: Boolean, default: false },
    mainRole: { type: Object, default: () => ({}) },
    schemeCount: { type: Number, default: 3 }
  },
  data() {
    return {
      schemes: [],
      activeSchemeIndex: 0,
      currentTeamId: 0,
      partners: [],
      partnersByPev: {},
      availablePevs: [],
      selectedPev: null,
      selectedPartnerId: 0,
      showSelector: false,
      selectingPos: '',
      // 拖拽临时状态
      draggingPos: '',
      dragOverPos: '',
      // 触摸拖拽状态
      touchStartPos: null,
      touchStartElement: null,
      touchStartTime: 0,
      isDragging: false
    }
  },
  computed: {
    currentScheme() {
      return this.schemes[this.activeSchemeIndex] || { id: 0, slots: {}, modified: false }
    },
    // 新增：前后排位置数组，便于模板渲染
    frontPositions() {
      return ['front1', 'front2', 'front3']
    },
    backPositions() {
      return ['back1', 'back2', 'back3']
    },
    // 展示的品阶（仅1到5）
    displayPevs() {
      const allowed = [1, 2, 3, 4, 5]
      return (this.availablePevs || []).filter(p => allowed.includes(p))
    },
    // 当前Tab下的伙伴视图（无“全部”）
    partnersInTab() {
      const pev = (this.selectedPev ?? null) || (this.displayPevs[0] || null)
      if (!pev) return []
      return this.partnersByPev[pev] || []
    },
    // 当前选中卡槽是否有伙伴（id != 0）
    selectedMemberHasPartner() {
      try {
        if (!this.selectingPos) return false
        const m = this.currentScheme.slots?.[this.selectingPos]
        if (!m) return false
        const id = m.partner_id ?? m.id ?? 0
        return id !== 0
      } catch (e) {
        return false
      }
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.initialize()
      }
    }
  },
  created() {
    // 初始化默认方案
    for (let i = 0; i < this.schemeCount; i++) {
      this.schemes.push({ id: i + 1, slots: {}, modified: false })
    }
  },
  methods: {
    async initialize() {
      try {
        const apiMod = (await import('@/api')).default
        // 加载团队列表，并将 方案1/2/3 分别映射到 team_id 1/2/3
        const res = await apiMod.sect.getPartnerTeamList()
        if (res && res.code === 1 && res.data && Array.isArray(res.data.team)) {
          const teams = res.data.team
          const positions = [...this.frontPositions, ...this.backPositions]
          // 重建 schemes：按返回的团队依次映射到方案1/2/3
          this.schemes = teams.slice(0, this.schemeCount).map((team, idx) => {
            const slots = {}
            const members = team.members || []
            positions.forEach((key, i) => {
              slots[key] = members[i] || null
            })
            return { id: idx + 1, teamId: idx + 1, slots, modified: false }
          })
          this.activeSchemeIndex = 0
          this.currentTeamId = this.schemes[0]?.teamId || 1
        }
    
        // 加载伙伴列表（用于选择伙伴）
        const listRes = await apiMod.sect.getPartnerList()
        if (listRes && listRes.code === 1 && listRes.data) {
          this.partners = listRes.data.partners || listRes.data || []
        }
    
        // 尝试加载已保存的方案：保持映射 方案1/2/3 -> team_id 1/2/3
        const saved = localStorage.getItem('lineup_schemes')
        if (saved) {
          const parsed = JSON.parse(saved)
          if (Array.isArray(parsed) && parsed.length) {
            this.schemes = parsed.slice(0, this.schemeCount).map((it, idx) => ({
              id: idx + 1,
              teamId: idx + 1,
              slots: it.slots || {},
              modified: false
            }))
            this.activeSchemeIndex = 0
            this.currentTeamId = this.schemes[0]?.teamId || 1
          }
        }
      } catch (e) {
        console.error('初始化阵容弹框失败:', e)
      }
    },
    addScheme() {
      this.schemes.push({ id: this.schemes.length + 1, slots: {}, modified: false })
    },
    switchScheme(idx) {
      this.activeSchemeIndex = idx
      // 切换方案时更新当前 team_id 映射：方案1/2/3 -> team_id 1/2/3
      const scheme = this.schemes[idx]
      if (scheme && scheme.teamId) {
        this.currentTeamId = scheme.teamId
      } else {
        this.currentTeamId = idx + 1
      }
    },
    openPartnerSelector(posKey) {
      this.selectingPos = posKey
      this.showSelector = true
      this.partners = []
      this.selectedPartnerId = 0
      // 点击时再请求所有伙伴接口（懒加载，不使用搜索）
      this.fetchPartners()
    },
    closePartnerSelector() {
      this.showSelector = false
      this.selectingPos = ''
    },
    closeSelector() {
      this.closePartnerSelector()
    },
    selectPartner(p) {
      if (!this.selectingPos) return
      const member = {
        partner_id: p.partner_id || p.id || 0,
        name: p.name || '未知',
        pev: typeof p.pev === 'number' ? p.pev : this.getQualityNumber(p.quality) || 1,
        hp: p.hp || 0,
        base_damage: p.base_damage || 0
      }
      this.$set(this.currentScheme.slots, this.selectingPos, member)
      this.currentScheme.modified = true
      this.closePartnerSelector()
      // 选择后立即同步到后端
      this.notifyFormationChange()
    },
    onPartnerSelectChange() {
      const id = Number(this.selectedPartnerId)
      if (!id) return
      const list = this.partnersInTab || []
      const p = list.find(it => (it.partner_id ?? it.id) === id)
      if (p) {
        this.selectPartner(p)
      }
    },
    removePartner() {
      if (!this.selectingPos) return
      this.$set(this.currentScheme.slots, this.selectingPos, null)
      this.closePartnerSelector()
      this.notifyFormationChange()
    },
    resetScheme() {
      this.currentScheme.slots = {}
      this.currentScheme.modified = true
    },
    async saveScheme() {
      try {
        const toSave = this.schemes.map(s => ({ slots: s.slots }))
        localStorage.setItem('lineup_schemes', JSON.stringify(toSave))
        this.currentScheme.modified = false
        this.$emit('saved', toSave)
        uni.showToast && uni.showToast({ title: '保存成功', icon: 'success' })
      } catch (e) {
        console.error('保存方案失败:', e)
        uni.showToast && uni.showToast({ title: '保存失败', icon: 'none' })
      }
    },
    async applyScheme() {
      try {
        const order = [...this.frontPositions, ...this.backPositions]
        const partnerIds = order.map(key => {
          const m = this.currentScheme.slots[key]
          return m ? m.partner_id : 0
        })
        const res = await api.sect.partnerJoinTeam(this.currentTeamId, partnerIds)
        if (res && res.code === 1) {
          uni.showToast && uni.showToast({ title: '应用成功', icon: 'success' })
          this.$emit('applied', { schemeIndex: this.activeSchemeIndex, partnerIds })
        } else {
          uni.showToast && uni.showToast({ title: (res && res.message) || '应用失败', icon: 'none' })
        }
      } catch (e) {
        console.error('应用方案失败:', e)
        uni.showToast && uni.showToast({ title: '网络错误', icon: 'none' })
      }
    },
    getPosName(posKey) {
      const map = {
        front1: '前排一',
        front2: '前排二',
        front3: '前排三',
        back1: '后排一',
        back2: '后排二',
        back3: '后排三'
      }
      return map[posKey] || posKey
    },
    close() {
      this.$emit('close')
    },
    onMaskClick() {
      // 点击遮罩关闭
      this.close()
    },
    onDragStart(posKey, event) {
      this.draggingPos = posKey
      if (event && event.dataTransfer) {
        event.dataTransfer.effectAllowed = 'move'
        event.dataTransfer.setData('text/plain', posKey)
      }
    },
    onDragOver(posKey, event) {
      if (event) {
        event.preventDefault()
        if (this.draggingPos && this.draggingPos !== posKey) {
          this.dragOverPos = posKey
          if (event.dataTransfer) {
            event.dataTransfer.dropEffect = 'move'
          }
        }
      }
    },
    async onDrop(targetPosKey, event) {
      if (event) {
        event.preventDefault()
      }
      if (!this.draggingPos || this.draggingPos === targetPosKey) {
        this.dragOverPos = ''
        return
      }
      // 伙伴之间（含玩家）互换
      const a = this.currentScheme.slots[this.draggingPos]
      const b = this.currentScheme.slots[targetPosKey]
      this.$set(this.currentScheme.slots, this.draggingPos, b)
      this.$set(this.currentScheme.slots, targetPosKey, a)
      this.currentScheme.modified = true
      // 通知后端更新位置
      await this.notifyFormationChange()
      this.dragOverPos = ''
    },
    onDragEnd() {
      this.draggingPos = ''
      this.dragOverPos = ''
    },
    // ========== 触摸事件处理（移动端） ==========
    onTouchStart(posKey, event) {
      // 记录触摸开始位置和时间
      const touch = event.touches[0]
      this.touchStartPos = {
        x: touch.clientX,
        y: touch.clientY,
        posKey: posKey
      }
      this.touchStartElement = event.currentTarget
      this.touchStartTime = Date.now()
      this.isDragging = false
      // 设置拖拽状态，显示视觉反馈
      this.draggingPos = posKey
    },
    onTouchMove(posKey, event) {
      if (!this.touchStartPos) return
      
      const touch = event.touches[0]
      const deltaX = Math.abs(touch.clientX - this.touchStartPos.x)
      const deltaY = Math.abs(touch.clientY - this.touchStartPos.y)
      const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY)
      
      // 移动距离超过10px才认为是拖拽，而不是点击
      if (distance > 10) {
        this.isDragging = true
        event.preventDefault() // 防止页面滚动
        
        // 使用更可靠的方法查找目标卡片
        try {
          const elementBelow = document.elementFromPoint(touch.clientX, touch.clientY)
          if (elementBelow) {
            const cardElement = elementBelow.closest('.lineup-card')
            if (cardElement) {
              // 通过data属性或遍历找到对应的posKey
              const allCards = Array.from(document.querySelectorAll('.lineup-card'))
              const cardIndex = allCards.indexOf(cardElement)
              const positions = [...this.frontPositions, ...this.backPositions]
              if (cardIndex >= 0 && cardIndex < positions.length) {
                const targetPosKey = positions[cardIndex]
                if (targetPosKey !== this.draggingPos) {
                  this.dragOverPos = targetPosKey
                } else {
                  this.dragOverPos = ''
                }
              }
            } else {
              this.dragOverPos = ''
            }
          } else {
            this.dragOverPos = ''
          }
        } catch (e) {
          // 某些环境下elementFromPoint可能不可用
          this.dragOverPos = ''
        }
      }
    },
    async onTouchEnd(posKey, event) {
      if (!this.touchStartPos) return
      
      const touchTime = Date.now() - this.touchStartTime
      const touch = event.changedTouches[0]
      const deltaX = Math.abs(touch.clientX - this.touchStartPos.x)
      const deltaY = Math.abs(touch.clientY - this.touchStartPos.y)
      const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY)
      
      // 查找结束触摸点下的元素
      let targetPosKey = null
      if (this.isDragging && distance > 10) {
        try {
          const elementBelow = document.elementFromPoint(touch.clientX, touch.clientY)
          if (elementBelow) {
            const cardElement = elementBelow.closest('.lineup-card')
            if (cardElement) {
              const allCards = Array.from(document.querySelectorAll('.lineup-card'))
              const cardIndex = allCards.indexOf(cardElement)
              const positions = [...this.frontPositions, ...this.backPositions]
              if (cardIndex >= 0 && cardIndex < positions.length) {
                targetPosKey = positions[cardIndex]
              }
            }
          }
        } catch (e) {
          console.warn('Touch event error:', e)
        }
        
        // 如果找到了目标位置或已经有dragOverPos，执行交换
        const finalTarget = targetPosKey || this.dragOverPos
        if (finalTarget && finalTarget !== this.draggingPos) {
          await this.swapPositions(this.draggingPos, finalTarget)
        }
      } else if (!this.isDragging && touchTime < 300 && distance < 10) {
        // 如果移动距离很小且时间短，认为是点击
        this.handleCardClick(posKey, event)
      }
      
      // 重置状态
      this.draggingPos = ''
      this.dragOverPos = ''
      this.touchStartPos = null
      this.touchStartElement = null
      this.isDragging = false
    },
    async swapPositions(fromPos, toPos) {
      if (fromPos === toPos) return
      
      const a = this.currentScheme.slots[fromPos]
      const b = this.currentScheme.slots[toPos]
      this.$set(this.currentScheme.slots, fromPos, b)
      this.$set(this.currentScheme.slots, toPos, a)
      this.currentScheme.modified = true
      // 通知后端更新位置
      await this.notifyFormationChange()
    },
    handleCardClick(posKey, event) {
      // 如果是拖拽操作，不触发点击
      if (this.isDragging) {
        return
      }
      // 延迟一下，确保触摸事件已处理完
      setTimeout(() => {
        if (!this.isDragging) {
          this.openPartnerSelector(posKey)
        }
      }, 100)
    },
    async notifyFormationChange() {
      try {
        const order = [...this.frontPositions, ...this.backPositions]
        const partnerIds = order.map(key => {
          const m = this.currentScheme.slots[key]
          // 未配置则传0；玩家传-1；伙伴传具体ID
          if (!m) return 0
          return typeof m.partner_id === 'number' ? m.partner_id : (m.id || 0)
        })
        const res = await api.sect.partnerJoinTeam(this.currentTeamId, partnerIds)
        if (res && res.code === 1) {
          // 成功不提示，避免频繁toast
        } else {
          uni.showToast && uni.showToast({ title: (res && res.message) || '阵容更新失败', icon: 'none' })
        }
      } catch (e) {
        console.error('通知后端更新阵容失败:', e)
        uni.showToast && uni.showToast({ title: '网络错误', icon: 'none' })
      }
    },
    async clearFormation() {
      try {
        const order = [...this.frontPositions, ...this.backPositions]
        const partnerIds = order.map(key => {
          const m = this.currentScheme.slots[key]
          if (m && m.partner_id === -1) return -1
          return 0
        })
        const res = await api.sect.partnerJoinTeam(this.currentTeamId, partnerIds)
        if (res && res.code === 1) {
          // 更新本地slots，保留主角，其余清空
          order.forEach((key, idx) => {
            const pid = partnerIds[idx]
            if (pid === -1) {
              // 保留主角
              const m = this.currentScheme.slots[key]
              this.$set(this.currentScheme.slots, key, m || { partner_id: -1, name: '主角', pev: 1, hp: 0, base_damage: 0 })
            } else {
              this.$set(this.currentScheme.slots, key, null)
            }
          })
          this.currentScheme.modified = true
          uni.showToast && uni.showToast({ title: '已清空阵容', icon: 'success' })
        } else {
          uni.showToast && uni.showToast({ title: (res && res.message) || '清空失败', icon: 'none' })
        }
      } catch (e) {
        console.error('清空阵容失败:', e)
        uni.showToast && uni.showToast({ title: '网络错误', icon: 'none' })
      }
    },
    async fetchPartners() {
      try {
        const res = await api.sect.getPartnerList(0)
        if (res && res.code === 1) {
          // 支持后端返回为 map：{ "1": [...], "2": [...], ... }
          const rawMap = res?.data || {}
          // 如果存在 data.partners 这种数组也兼容
          const maybeArray = res?.data?.partners || res?.data?.list

          if (Array.isArray(maybeArray)) {
            this.partners = maybeArray.map(p => {
              const id = p.partner_id ?? p.id
              const name = p.name ?? '未知'
              const level = p.level ?? 1
              const star = p.star ?? 0
              const type = p.type ?? 'damage'
              const avatar = p.avatar ?? 'default-avatar.svg'
              const qualityStr = (p.quality ?? this.mapQualityToString(p.pev))
              const pev = typeof p.pev === 'number' ? p.pev : this.getQualityNumber(qualityStr)
              return { id, partner_id: id, name, level, star, type, avatar, quality: qualityStr, pev, hp: p.hp ?? 0, base_damage: p.base_damage ?? 0 }
            })
            this.availablePevs = []
            this.partnersByPev = {}
            this.selectedPev = null
            this.selectedPartnerId = 0
            return
          }

          // map结构解析
          if (rawMap && typeof rawMap === 'object') {
            const pevs = Object.keys(rawMap)
              .map(k => Number(k))
              .filter(n => !Number.isNaN(n))
              .sort((a, b) => a - b)

            const byPev = {}
            const all = []
            pevs.forEach(pev => {
              const arr = Array.isArray(rawMap[String(pev)]) ? rawMap[String(pev)] : []
              byPev[pev] = arr.map(p => {
                const id = p.partner_id ?? p.id
                const name = p.name ?? '未知'
                const level = p.level ?? 1
                const star = p.star ?? 0
                const type = p.type ?? 'damage'
                const avatar = p.avatar ?? 'default-avatar.svg'
                const pevNum = typeof p.pev === 'number' ? p.pev : pev
                const qualityStr = this.mapQualityToString(pevNum)
                const normalized = { id, partner_id: id, name, level, star, type, avatar, quality: qualityStr, pev: pevNum, hp: p.hp ?? 0, base_damage: p.base_damage ?? 0 }
                all.push(normalized)
                return normalized
              })
            })
            this.partnersByPev = byPev
            this.availablePevs = pevs
            this.partners = all
            // 默认选中1-5中最小的存在的品阶
            const allowed = [1,2,3,4,5]
            const def = pevs.find(p => allowed.includes(p)) || (pevs[0] || null)
            this.selectedPev = def
            this.selectedPartnerId = 0
          }
        }
      } catch (e) {
        console.error('加载伙伴列表失败:', e)
        this.partners = []
        this.partnersByPev = {}
        this.availablePevs = []
        this.selectedPev = null
        this.selectedPartnerId = 0
      }
    },
    getAvatarUrl(avatar) {
      if (!avatar) return '/static/default-avatar.svg'
      if (typeof avatar === 'string' && avatar.includes('.') && !avatar.includes('/')) {
        return `/static/${avatar}`
      }
      return `/static/avatars/${avatar}`
    },
    getTypeText(type) {
      const typeMap = { tank: '坦克', damage: '输出', healer: '治疗', control: '控制' }
      return typeMap[type] || (type || '输出')
    },
    getQualityNumber(quality) {
      const map = { white: 1, green: 2, blue: 3, purple: 4, orange: 5, red: 6 }
      if (typeof quality === 'number') return quality
      return map[quality] || 1
    },
    mapQualityToString(pev) {
      const map = { 1: 'white', 2: 'green', 3: 'blue', 4: 'purple', 5: 'orange', 6: 'red' }
      return map[pev] || 'white'
    },
    isPartnerInFormation(p) {
      const id = p.partner_id ?? p.id
      const order = [...this.frontPositions, ...this.backPositions]
      const ids = order.map(key => {
        const m = this.currentScheme.slots[key]
        return m ? (m.partner_id ?? m.id ?? 0) : 0
      })
      return ids.includes(id)
    }
  }
}
</script>

<style scoped>
/* ========== 武侠风格阵容弹框 ========== */
.lineup-modal-wrapper {
  position: fixed;
  inset: 0;
  background: rgba(75, 58, 42, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  backdrop-filter: blur(4px);
  font-family: "STSong", "Noto Serif SC", serif;
}
.lineup-modal {
  width: min(95%, 600px);
  max-height: 90vh;
  background: rgba(248, 246, 241, 0.98);
  border-radius: 16px;
  box-shadow: 0 10px 40px rgba(139, 111, 71, 0.5);
  border: 4px solid #8b6f47;
  overflow: hidden;
  animation: popIn 250ms ease-out;
  display: flex;
  flex-direction: column;
}
@keyframes popIn {
  from { transform: translateY(12px) scale(0.98); opacity: 0; }
  to { transform: translateY(0) scale(1); opacity: 1; }
}
.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 20px;
  background: linear-gradient(135deg, #8b6f47 0%, #6b4f3b 100%);
  color: white;
  border-bottom: 3px solid #4b3a2a;
}
.modal-title { 
  font-weight: 700; 
  font-size: 20px; 
  letter-spacing: 2px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}
.modal-subtitle { 
  margin-left: 10px; 
  font-size: 13px; 
  opacity: 0.9; 
  font-weight: 600;
}
.header-actions { display: flex; gap: 10px; }
.header-btn { 
  background: rgba(255,255,255,0.2); 
  border: 2px solid rgba(255,255,255,0.3); 
  color: white; 
  padding: 6px 12px; 
  border-radius: 10px; 
  cursor: pointer; 
  font-weight: 700;
  font-size: 13px;
  transition: all 0.3s ease;
}
.header-btn:hover {
  background: rgba(255,255,255,0.3);
  border-color: rgba(255,255,255,0.5);
  transform: translateY(-1px);
}
.header-btn.close { background: rgba(0,0,0,0.3); }

.scheme-tabs { 
  display: flex; 
  gap: 10px; 
  padding: 15px 20px; 
  background: rgba(232, 220, 196, 0.5);
  border-bottom: 2px solid #d8c7a3;
  overflow-x: auto;
}
.tab-item { 
  padding: 8px 16px; 
  border-radius: 12px; 
  border: 2px solid #d8c7a3; 
  cursor: pointer; 
  background: rgba(255,255,255,0.9); 
  font-weight: 600;
  font-size: 14px;
  color: #6b4f3b;
  transition: all 0.3s ease;
  white-space: nowrap;
}
.tab-item:hover {
  border-color: #c4a57b;
  background: rgba(255,255,255,1);
}
.tab-item.active { 
  border-color: #8b6f47; 
  background: linear-gradient(135deg, #8b6f47 0%, #6b4f3b 100%);
  color: white;
  box-shadow: 0 3px 10px rgba(139, 111, 71, 0.3);
}
.tab-name { font-weight: 700; }
.tab-status { margin-left: 8px; font-size: 11px; color: #d4af37; font-weight: 700; }

/* ========== 阵容展示区域 - 武侠风格 ========== */
.formation-area { 
  display: flex; 
  flex-direction: column; 
  gap: 20px; 
  padding: 20px; 
  flex: 1;
  overflow-y: auto;
}
.row { 
  display: flex; 
  justify-content: center; 
  align-items: center;
  gap: 15px; 
  flex-wrap: nowrap;
}
.front-row { 
  margin-bottom: 15px;
}
.back-row { 
  margin-top: 15px;
}

/* ========== 阵容卡片 - 武侠风格 ========== */
.lineup-card { 
  flex: 1;
  max-width: 180px;
  min-width: 0;
  background: rgba(255,255,255,0.98); 
  border-radius: 12px; 
  border: 3px solid #c4a57b; 
  box-shadow: 0 5px 15px rgba(139, 111, 71, 0.25); 
  overflow: hidden; 
  transition: all 0.3s ease;
  cursor: move;
  position: relative;
}
.lineup-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 7px 20px rgba(139, 111, 71, 0.35);
  border-color: #8b6f47;
}
.lineup-card.dragging {
  opacity: 0.5;
  transform: scale(0.95);
}
.lineup-card.drag-over {
  border-color: #8b6f47;
  box-shadow: 0 0 0 3px rgba(139, 111, 71, 0.3);
  background: rgba(139, 111, 71, 0.1);
}
.lineup-card .slot-body { 
  display: flex; 
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 6px; 
  padding: 10px 8px; 
  min-height: 80px; 
  text-align: center;
}
.lineup-card .role-info { 
  display: flex; 
  flex-direction: column; 
  gap: 8px; 
  width: 100%;
}
.lineup-card .empty-tip { 
  color: #8b6f47; 
  font-size: 13px; 
  font-weight: 600;
  font-style: italic;
}
.lineup-card .role-stats { 
  display: flex; 
  flex-direction: column;
  gap: 3px; 
  font-size: 11px; 
  color: #6b4f3b; 
  font-weight: 600;
  background: rgba(139, 111, 71, 0.06);
  padding: 4px 8px;
  border-radius: 6px;
  border: 1px solid #d8c7a3;
  width: 100%;
  box-sizing: border-box;
}
.lineup-card .role-stats span {
  font-size: 10px;
  white-space: nowrap;
}

/* 响应式：小屏缩放卡片尺寸与栅格间距，保持居中与完整性 */
@media (max-width: 960px) {
  .lineup-card { 
    max-width: 150px;
    border-width: 2px;
  }
  .lineup-card .slot-body {
    padding: 8px 6px;
    min-height: 70px;
    gap: 4px;
  }
}
@media (max-width: 640px) {
  .lineup-modal {
    width: 98%;
    border-width: 3px;
    max-height: 95vh;
  }
  .formation-area { 
    padding: 10px 8px; 
    gap: 12px; 
  }
  .row { 
    gap: 6px; 
  }
  .lineup-card { 
    max-width: none;
    flex: 1;
    min-width: 0;
    border-width: 2px;
  }
  .lineup-card .slot-body {
    padding: 8px 6px;
    min-height: 65px;
    gap: 4px;
  }
  .lineup-card .role-stats {
    font-size: 11px;
    padding: 4px 6px;
  }
  .lineup-card .empty-tip {
    font-size: 11px;
  }
  .modal-header {
    padding: 12px 15px;
  }
  .modal-title {
    font-size: 18px;
  }
  .modal-actions {
    padding: 12px 15px;
    gap: 8px;
  }
  .action-btn {
    padding: 8px 14px;
    font-size: 13px;
  }
  .scheme-tabs {
    padding: 12px 15px;
    gap: 8px;
  }
  .tab-item {
    padding: 6px 12px;
    font-size: 13px;
  }
}
/* ========== 操作按钮 - 武侠风格 ========== */
.modal-actions { 
  display: flex; 
  gap: 12px; 
  justify-content: flex-end; 
  padding: 15px 20px; 
  background: rgba(232, 220, 196, 0.3);
  border-top: 2px solid #d8c7a3;
}
.action-btn { 
  background: rgba(255,255,255,0.9); 
  border: 3px solid #c4a57b; 
  border-radius: 12px; 
  padding: 10px 20px; 
  cursor: pointer; 
  transition: all 0.3s ease; 
  font-weight: 700;
  font-size: 14px;
  color: #4a3c2a;
  letter-spacing: 0.5px;
}
.action-btn:hover { 
  transform: translateY(-2px); 
  box-shadow: 0 5px 15px rgba(139, 111, 71, 0.3); 
}
.action-btn.primary { 
  background: linear-gradient(135deg, #8b6f47 0%, #6b4f3b 100%); 
  color: white; 
  border-color: #4b3a2a;
}
.action-btn.primary:hover {
  box-shadow: 0 6px 18px rgba(75, 58, 42, 0.4);
}
.action-btn.danger { 
  background: linear-gradient(135deg, #c94a3f 0%, #a83931 100%); 
  color: white; 
  border-color: #7a2923;
}
.action-btn.danger:hover {
  box-shadow: 0 6px 18px rgba(169, 57, 49, 0.4);
}

/* ========== 伙伴选择弹层 - 武侠风格 ========== */
.selector-wrapper {
  position: fixed;
  inset: 0;
  background: rgba(75, 58, 42, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10000;
  backdrop-filter: blur(4px);
}
.selector-panel {
  width: min(85%, 500px);
  max-height: 70vh;
  background: rgba(248, 246, 241, 0.98);
  border-radius: 16px;
  box-shadow: 0 10px 40px rgba(139, 111, 71, 0.5);
  border: 4px solid #8b6f47;
  padding: 20px;
  overflow-y: auto;
}
.selector-header { 
  display: flex; 
  justify-content: space-between; 
  align-items: center; 
  margin-bottom: 15px; 
  padding-bottom: 12px;
  border-bottom: 2px solid #d8c7a3;
}
.selector-title { 
  font-weight: 700; 
  font-size: 18px; 
  color: #4a3c2a; 
  letter-spacing: 1px;
}
.selector-close { 
  cursor: pointer; 
  font-size: 22px; 
  background: rgba(139, 111, 71, 0.1); 
  border: 2px solid #c4a57b;
  border-radius: 50%; 
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #6b4f3b;
  font-weight: 700;
  transition: all 0.3s ease;
}
.selector-close:hover {
  background: rgba(139, 111, 71, 0.2);
  border-color: #8b6f47;
}

/* ========== 品阶筛选Tabs - 武侠风格 ========== */
.selector-tabs { 
  display: flex; 
  gap: 8px; 
  margin: 12px 0 15px; 
  flex-wrap: wrap;
}
.selector-tabs .tab-item { 
  padding: 8px 14px; 
  border-radius: 10px; 
  background: rgba(255,255,255,0.9); 
  color: #6b4f3b; 
  font-size: 13px; 
  cursor: pointer; 
  user-select: none; 
  transition: all 0.3s ease; 
  border: 2px solid #d8c7a3;
  font-weight: 600;
}
.selector-tabs .tab-item:hover { 
  background: rgba(255,255,255,1);
  border-color: #c4a57b;
}
.selector-tabs .tab-item.active { 
  background: linear-gradient(135deg, #8b6f47 0%, #6b4f3b 100%); 
  color: white; 
  border-color: #4b3a2a;
  box-shadow: 0 3px 10px rgba(139, 111, 71, 0.3);
}

/* ========== 下拉选择样式 - 武侠风格 ========== */
.selector-controls { 
  display: flex; 
  flex-direction: column;
  gap: 10px; 
  margin-bottom: 15px; 
}
.selector-label { 
  font-size: 14px; 
  color: #6b4f3b; 
  font-weight: 700;
}
.partner-select { 
  flex: 1; 
  padding: 10px 12px; 
  border-radius: 10px; 
  border: 2px solid #c4a57b; 
  background: rgba(255,255,255,0.9); 
  color: #4a3c2a;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s ease;
}
.partner-select:focus {
  outline: none;
  border-color: #8b6f47;
  box-shadow: 0 0 0 3px rgba(139, 111, 71, 0.1);
}
.remove-btn { 
  margin-top: 10px; 
  padding: 10px 16px; 
  border-radius: 10px; 
  background: linear-gradient(135deg, #fff5f5 0%, #ffe8e8 100%); 
  color: #c94a3f; 
  border: 2px solid #f5c2c2; 
  cursor: pointer; 
  font-weight: 700;
  font-size: 13px;
  transition: all 0.3s ease;
}
.remove-btn:hover {
  background: linear-gradient(135deg, #ffe8e8 0%, #ffd6d6 100%);
  border-color: #e8a8a8;
  transform: translateY(-1px);
  box-shadow: 0 3px 10px rgba(201, 74, 63, 0.2);
}

.partners-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 12px;
}
.partner-card {
  background: rgba(255,255,255,0.95);
  border-radius: 14px;
  padding: 12px;
  text-align: center;
  box-shadow: 0 6px 18px rgba(0,0,0,0.1);
  transition: all 0.2s ease;
  position: relative;
  border: 2px solid rgba(255,255,255,0.6);
}
.partner-card:active { transform: translateY(-2px); box-shadow: 0 10px 24px rgba(0,0,0,0.15); }
.partner-avatar { position: relative; width: 96px; height: 96px; margin: 0 auto 8px; }
.avatar-img { width: 100%; height: 100%; border-radius: 10px; }
.quality-border { position: absolute; inset: -4px; border: 4px solid; border-radius: 14px; pointer-events: none; }
.quality-border.quality-green { border-color: #52c41a; }
.quality-border.quality-blue { border-color: #1890ff; }
.quality-border.quality-purple { border-color: #722ed1; }
.quality-border.quality-orange { border-color: #fa8c16; }
.quality-border.quality-red { border-color: #ff4d4f; }
.partner-card.card-white { border-color: rgba(255,255,255,0.8); }
.partner-card.card-green { border-color: #52c41a; box-shadow: 0 6px 20px rgba(82,196,26,0.25); }
.partner-card.card-blue { border-color: #1890ff; box-shadow: 0 6px 20px rgba(24,144,255,0.25); }
.partner-card.card-purple { border-color: #722ed1; box-shadow: 0 6px 20px rgba(114,46,209,0.25); }
.partner-card.card-orange { border-color: #fa8c16; box-shadow: 0 6px 20px rgba(250,140,22,0.25); }
.partner-card.card-red { border-color: #ff4d4f; box-shadow: 0 6px 20px rgba(255,77,79,0.25); }
.star-rating { position: absolute; bottom: -6px; left: 50%; transform: translateX(-50%); display: flex; }
.star { color: #ffd700; font-size: 14px; text-shadow: 1px 1px 2px rgba(0,0,0,0.3); }
.partner-name { font-weight: 700; margin-bottom: 6px; }
.partner-stats { font-size: 13px; color: #333; font-weight: 600; margin-bottom: 6px; background: rgba(102,126,234,0.08); border-radius: 10px; padding: 4px 8px; }
.stat-label { color: #222; font-weight: 700; }
.status-indicator { padding: 4px 10px; border-radius: 12px; font-size: 12px; background-color: #f0f0f0; color: #999; display: inline-block; }
.status-indicator.active { background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%); color: #333; }
.remove-card { display: flex; align-items: center; background: rgba(255,255,255,0.95); padding: 12px; border-radius: 14px; box-shadow: 0 6px 18px rgba(0,0,0,0.1); border: 1px solid rgba(255,255,255,0.3); transition: all 0.2s ease; }
.remove-card:active { transform: translateY(-2px); box-shadow: 0 10px 24px rgba(0,0,0,0.15); }
.action-icon { font-size: 22px; margin-right: 10px; }
.action-title { font-size: 16px; font-weight: 700; color: #333; margin-bottom: 4px; }
.action-desc { font-size: 13px; color: #666; }

@media (max-width: 640px) {
  .partners-grid { grid-template-columns: repeat(2, 1fr); }
  .partner-avatar { width: 80px; height: 80px; }
}

/* 弹层过渡 */
.fade-slide-enter-active, .fade-slide-leave-active { transition: all .18s ease; }
.fade-slide-enter, .fade-slide-leave-to { opacity: 0; transform: translateY(8px); }
</style>